package workpool

import "github.com/mars/pkg/loggers"

type Payload interface {
	Payload() error
}

type PayloadFunc func() error

func (f PayloadFunc) Payload() error {
	return f()
}

type Job struct {
	Payload Payload
}

type Worker struct {
	Id         int
	WorkerPool chan chan Job
	JobChan    chan Job
	quit       chan struct{}
}

func NewWorker(workerPool chan chan Job, id int) Worker {
	return Worker{
		Id:         id,
		WorkerPool: workerPool,
		JobChan:    make(chan Job),
		quit:       make(chan struct{}),
	}
}

func (w Worker) Start() {
	go func() {
		defer func() {
			if err := recover(); err != nil {
				loggers.Errorf("execute job painc: %v", err)
			}
		}()
		for {
			w.WorkerPool <- w.JobChan
			select {
			case job := <-w.JobChan:
				if err := job.Payload.Payload(); err != nil {
					loggers.Errorf("execute job err: %v", err)
				}
			case <-w.quit:
				loggers.Infof("worker Num %d stopped", w.Id)
				return
			}
		}
	}()
}

func (w Worker) Shutdown() {
	w.quit <- struct{}{}
}
